package org.fxkj.cloud.uaa.service.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.fxkj.cloud.uaa.service.security.AuthenticationConstant;
import org.fxkj.cloud.uaa.service.security.model.token.JwtTokenFactory;
import org.fxkj.cloud.uaa.service.security.model.token.RawAccessJwtToken;
import org.fxkj.cloud.uaa.service.security.model.token.RefreshAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.IOException;

/**
 * <p>Description: </p>
 *
 * @author Wei, Wu
 * @create 2024/10/22 8:35
 */
public class WRefreshAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public static final String REFRESH_TOKEN_URI = "/refreshToken";
    private final JwtTokenFactory jwtTokenFactory;
    private final ObjectMapper objectMapper;

    public WRefreshAuthenticationFilter(AntPathRequestMatcher matcher, JwtTokenFactory jwtTokenFactory, ObjectMapper objectMapper) {
        super(matcher);
        this.jwtTokenFactory = jwtTokenFactory;
        this.objectMapper = objectMapper;
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {

        String token = request.getParameter(AuthenticationConstant.REFRESH_TOKEN);
        if (StringUtils.isEmpty(token)) {
            throw new ServletException("刷新token不可为空");
        }

        RawAccessJwtToken refreshToken = new RawAccessJwtToken(token);
        return this.getAuthenticationManager().authenticate(new RefreshAuthenticationToken(refreshToken));
    }
}
